package com.GLM.Viewer.FirstLogin;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.text.SpannableString;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UserInfoEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.Image.AvatarUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Main.MainActivity;
import com.GLM.Viewer.Map.MapMainActivity;

public class RegisterSecondViewActivity extends Activity {
	private final String TAG = "RegisterSecondViewActivity";
	private final static int UPLOADING_INFO = 1;
	private final static int UPLOADED_INFO = 2;
	private View mRegisterInputField;
	private TextView mRegisterInputTextView;
	private EditText mRegisterInputEditText;
	private Animation mAnimIn;
	private Animation mAnimOut;

	private Button mStep1Button;
	private Button mStep2Button;
	private Button mStep3Button;
	private InputMethodManager imm;

	ImageView avatarView;
	private HashMap<String, String> registerFirstViewData;
	private String mEmail;
	private Bitmap mDrawableAvater;
	private double[] mGeoLocation;
	private Address mAddress;
	
	private String takePhotoPath;
	private String fromalbumPath;
	private boolean takePhoto = false;
	private boolean fromAlbum = false;
	public String photoName;
	private ProgressDialog pd;
	private String username;
	private String password;
	private String nickname;
	private int userid;
	int status = -1;
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case UPLOADING_INFO:
				
				pd = ProgressDialog.show(RegisterSecondViewActivity.this, "", getString(R.string.dataupdate), true, true);
				thread = new Thread(new Runnable() {
					
					public void run() {
						// TODO Auto-generated method stub
						Looper.prepare();
						try {
							if((fromAlbum || takePhoto) && photoName != null)
								uploadFile();
						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						status = registerAndLogin();
						mHandler.sendEmptyMessage(UPLOADED_INFO);
						Looper.loop();
					}
				});
				thread.start();
				
				break;
			case UPLOADED_INFO:
				if(pd != null && pd.isShowing()){
					pd.cancel();
				}
				if(status == Constant.RESP_STATUS_SUCCESS){
					SharedPreferences sp = getSharedPreferences(Constant.SHAREDNAME, MODE_PRIVATE);
					Editor editor = sp.edit();
					editor.putBoolean(Constant.MAINACTIVITY, false);
					editor.putBoolean(Constant.PARTYMAINACTIVITY, false);
					editor.putBoolean(Constant.PARTYPLACEACTIVITY, false);
					editor.putBoolean(Constant.MEETINGPLACEACTIVITY, false);
					editor.putBoolean(Constant.MESSAGEACTIVITY, false);
					editor.putBoolean(Constant.FANSFRIENDACTIVITY, false);
					editor.putBoolean(Constant.FRIENDGROUPACTIVITY, false);
					editor.commit();
					Intent intent = new Intent(getApplicationContext(), MainActivity.class);
					startActivity(intent);
					finish();
				}
				break;
			default:
				break;
			}
		};
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_register_second);
		receiveDataFromRegisterFirstView();
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		
		mRegisterInputField = findViewById(R.id.register_inputfield);
		mRegisterInputField.setVisibility(View.GONE);
		initAnimation();

		mRegisterInputTextView = (TextView) findViewById(R.id.inputfield_title);
		mRegisterInputEditText = (EditText) findViewById(R.id.inputfield_edittext);

		mStep1Button = (Button) findViewById(R.id.registerbutton_step1);
		initStep1Button();

		mStep2Button = (Button) findViewById(R.id.registerbutton_step2);
		initStep2Button();

		mStep3Button = (Button) findViewById(R.id.registerbutton_step3);
		initStep3Button();

		initRegisterInputFieldButton();

	}

	@SuppressWarnings("unchecked")
	private void receiveDataFromRegisterFirstView() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			registerFirstViewData = (HashMap<String, String>) bundle.get(Constant.REGISTER_DATA);
		}
	}

	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}

	private void initStep1Button() {
		mStep1Button.setText(null);
		String line1 = getString(R.string.registersecond_unreg_step1_line1);
		String line2 = getString(R.string.registersecond_unreg_step1_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep1Button.append(spanText);
	}

	private void initStep1ButtonAfterVerified(String email) {
		mStep1Button.setText(null);
		String line1 = getString(R.string.registerfirst_reg_step1_line1);
		String line2 = getString(R.string.registerfirst_reg_step1_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2 + email);
		mStep1Button.append(spanText);
		showNextRegisterView();
	}

	private void initStep2Button() {
		String line1 = getString(R.string.registersecond_unreg_step2_line1);
		String line2 = getString(R.string.registersecond_unreg_step2_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep2Button.append(spanText);
	}

	private void initStep2ButtonAfterVerified() {
		mStep2Button.setText(null);
		String line1 = getString(R.string.registersecond_reg_step2_line1);
		String line2 = getString(R.string.registersecond_reg_step2_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep2Button.append(spanText);
	}

	private void initStep3Button() {
		avatarView = (ImageView)findViewById(R.id.avatarView);
		String line1 = getString(R.string.registersecond_unreg_step3_line1);
		String line2 = getString(R.string.registersecond_unreg_step3_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep3Button.append(spanText);
	}

	private void initStep3ButtonAfterVerified() {
		mStep3Button.setText(null);
		String line1 = getString(R.string.registersecond_reg_step3_line1);
		String line2 = getString(R.string.registersecond_reg_step3_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep3Button.append(spanText);
	}

	private void showNextRegisterView() {
		if (mEmail != null) {
			Button nextButton = (Button) findViewById(R.id.gonext_button);
			nextButton.setVisibility(View.VISIBLE);
		}
	}

	private void initRegisterInputFieldButton() {
		Button inputCancelButton = (Button) findViewById(R.id.inputfield_cancelbutton);
		inputCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideRegisterInputField();
			}
		});

		Button inputOkButton = (Button) findViewById(R.id.inputfield_okbutton);
		inputOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				handleRegisterInputFieldOkButtenEvent();

			}
		});
	}

	private void showRegisterInputField() {
		mRegisterInputField.startAnimation(mAnimIn);
		mRegisterInputField.setVisibility(View.VISIBLE);
		mRegisterInputEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void hideRegisterInputField() {
		mRegisterInputEditText.setText("");
		mRegisterInputEditText.setInputType(InputType.TYPE_NULL);
		mRegisterInputEditText.clearFocus();
		mRegisterInputField.startAnimation(mAnimOut);
		mRegisterInputField.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	protected void handleRegisterInputFieldOkButtenEvent() {
		String step = (String) mRegisterInputTextView.getTag();
		if ("step1".equals(step)) {
			handleStep1RegisterInputFieldOkButtonEvent();
		}
	}

	private void handleStep1RegisterInputFieldOkButtonEvent() {
		String email = mRegisterInputEditText.getText().toString();
		if (!ViewsUtil.validateEmail(email)) {
			ViewsUtil.showErrorTip(this, R.string.registertip_email_wrongformat);
			return;
		}
		ViewsUtil.showErrorTip(this, R.string.registertip_email_verified);
		mEmail = email;
		initStep1ButtonAfterVerified(mEmail);
		hideRegisterInputField();
	}

	public void goBackButton_OnClick(View v) {
		Intent upIntent = new Intent(this, RegisterFirstViewActivity.class);
		upIntent.putExtra(Constant.REGISTER_DATA, registerFirstViewData);
		NavUtils.navigateUpTo(this, upIntent);
	}

	public void goNextButton_OnClick(View v) {
		if(username !=null && password != null && nickname != null)
		mHandler.sendEmptyMessage(UPLOADING_INFO);
//		registerAndLogin();
//		try {
//			uploadFile();
//		} catch (ClientProtocolException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

	public void registerStep1Button_OnClick(View v) {
		mRegisterInputTextView.setTag("step1");
		mRegisterInputTextView.setText(R.string.registersecond_inputfield_email);
		mRegisterInputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
		mRegisterInputEditText.setHint(R.string.registersecond_inputfieldtip_email);
		if (mEmail != null) {
			mRegisterInputEditText.setText(mEmail);
		}
		showRegisterInputField();
	}

	public void registerStep2Button_OnClick(View v) {
		Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.avater_set);
		builder.setNegativeButton(R.string.avater_album, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				intent.setType("image/*");
				startActivityForResult(Intent.createChooser(intent, "Selete Picture"), Constant.ACTIVITY_REQUESTCODE_ALBUM);
				
			}
		});
		builder.setPositiveButton(R.string.avater_takepicture, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_TAKEPICTURE);
			}
		});
		builder.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case Constant.ACTIVITY_REQUESTCODE_ALBUM:
				String str = checkImagePath(data);
				if(str != null){
					takePhoto = false;
					fromAlbum = true;
					String end = str.substring(str.lastIndexOf("."));
					int endindex = str.lastIndexOf("/")+1;
					String fpath = str.substring(0, endindex);
					File file = new File(str);
					String filename = formatDatetime(new Date(), "yyyyMMddHHmmsssss")+end;
					File newFile = new File(fpath+filename);
					file.renameTo(newFile);
					
					fromalbumPath = newFile.getAbsolutePath();
					Log.d("fromalbum", fromalbumPath);
					photoName = filename;
					Log.d("photoName", photoName);
					Log.d("ImageChoosepath", str);
				}
				startPhotoZoom(data.getData());
				break;
			case Constant.ACTIVITY_REQUESTCODE_TAKEPICTURE:
				String status = Environment.getExternalStorageState();
				if(!status.equals(Environment.MEDIA_MOUNTED)){
					Toast.makeText(RegisterSecondViewActivity.this, getString(R.string.sdcard_notin), Toast.LENGTH_LONG).show();
					return ;
				}
				Uri uri = data.getData();
				if(uri != null){
					mDrawableAvater = BitmapFactory.decodeFile(uri.getPath());
				}
				if(mDrawableAvater == null){
					Bundle bundle = data.getExtras();
					if(bundle != null){
						mDrawableAvater =  (Bitmap)bundle.get("data");
					}else{
						Toast.makeText(RegisterSecondViewActivity.this, "获取照片失败", Toast.LENGTH_LONG).show();
						return;
					}
				}
				
				FileOutputStream outputStream = null;
				photoName = formatDatetime(new Date(), "yyyyMMddHHmmsssss")+".jpg";
				String dirstr = Environment.getExternalStorageDirectory().toString() +"/glemei";
				File dir = new File(dirstr);
				
				if (!dir.exists()) {
					dir.mkdir(); 
				}
				File file = new File(dirstr, photoName);
				try {
					file.createNewFile();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				takePhotoPath = file.getAbsolutePath();
				Log.d("takePhotoPath", takePhotoPath);
				try {
					outputStream = new FileOutputStream(takePhotoPath);
					mDrawableAvater.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				Log.d("beginWriteImage", "begin");
				WriteImage();
				takePhoto = true;
				fromAlbum = false;
				avatarView.setVisibility(View.VISIBLE);
				avatarView.setBackgroundDrawable(AvatarUtil.Bitmap2Drawable(mDrawableAvater));
				
				break;
			case Constant.ACTIVITY_REQUESTCODE_NEWAVATER:
				Drawable newAvater = getNewAvater(data);
				if (newAvater != null) {
					avatarView.setVisibility(View.VISIBLE);
					avatarView.setBackgroundDrawable(newAvater);
				
					initStep2ButtonAfterVerified();
				}
				break;
			case Constant.ACTIVITY_REQUESTCODE_MAP:
				double[] loc;
				mAddress = (Address) data.getExtras().get("registerAddress");
				if (mAddress != null) {
					loc = new double[2];
					loc[0] = mAddress.getLatitude();
					loc[1] = mAddress.getLongitude();
					mGeoLocation = loc;
					Log.d(TAG, "lat -> " + loc[0] + " , long ->" + loc[1]);
				} else {
					mGeoLocation = data.getDoubleArrayExtra(Constant.LOCATION);
				}
				initStep3ButtonAfterVerified();
				break;
			default:
				break;

			}
			
		}
		
	}
	
	public static String formatDatetime(Date date, String format) {  
        DateFormat df = new SimpleDateFormat(format);  
        return df.format(date);  
    }  

	public void uploadFile() throws ClientProtocolException, IOException{
		File file = null;
		
		if(takePhoto){
			file = new File(takePhotoPath);
		}
		if(fromAlbum){
			file = new File(fromalbumPath);
		}
		
		 try {
//			 	URL url = new URL("http://192.168.3.100:8088/phpProject/push/android_upload.php?filename="+photoName);
	            URL url = new URL(Constant.URL_USER_AVAR +"?filename="+photoName);
	            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
	            httpUrlConnection.setDoOutput(true);
	            httpUrlConnection.setDoInput(true);
	            httpUrlConnection.setUseCaches(false);
	            httpUrlConnection.setRequestMethod("POST");
	            OutputStream os = httpUrlConnection.getOutputStream();
	            Thread.sleep(100);
	            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));

	            int bufSize = 0;
	            byte[] buffer = new byte[1024];
	            while ((bufSize = fis.read(buffer)) != -1) {
	                os.write(buffer, 0, bufSize);
	            }
	            fis.close();

	            String responMsg = httpUrlConnection.getResponseMessage();
	            Log.d(TAG, "responMsg =====" + responMsg);
	        } catch (Exception e) {
	           e.printStackTrace();
	        }
	
	}
	
	
	public void WriteImage() {
		try {
			FileInputStream fis = new FileInputStream(takePhotoPath);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[8192];
			int count = 0;
			while ((count = fis.read(buffer)) >= 0) {
				baos.write(buffer, 0, count);

			}
			fis.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String checkImagePath(Intent data){
		Cursor cursor = null;
		String path = null;
		try {
			Uri originalUri = data.getData();
			path = originalUri.toString();
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = managedQuery(originalUri, proj, null, null, null);
			if (cursor != null) {
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				// 最后根据索引值获取图片路径
				path = cursor.getString(column_index);
				Log.d("checkImagePath_path", path);
			}
		}
	    catch (Exception e) {
			Log.e("checkImage", e.getMessage());
		} finally {
			if (cursor != null && !cursor.isClosed()) 
				cursor.close();
		}
		
		return path;		
	}
	
	private Drawable getNewAvater(Intent data) {
		if (null != data) {
			Bundle bundle = data.getExtras();
			if (null != bundle) {
				Bitmap photo = bundle.getParcelable("data");
				Drawable drawable = new BitmapDrawable(photo);
				drawable.setBounds(0, 0, 100, 100);
				return drawable;
			}
		}
		return null;

	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_NEWAVATER);
	}

	public void registerStep3Button_OnClick(View v) {

		Intent intent = new Intent(this, MapMainActivity.class);
		intent.putExtra("ActivityIntent", "RegisterSecondActivity");
		startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_MAP);
	}

	private int registerAndLogin() {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = new JSONResponse();
		int status = -1;
		username = registerFirstViewData.get(Constant.REGISTER_DATA_USERNAME);
		password = registerFirstViewData.get(Constant.REGISTER_DATA_PASSWORD);
		nickname = registerFirstViewData.get(Constant.REGISTER_DATA_NICKNAME);
		try {
			jsonData.put(Constant.PARAM_ACCOUNT, username);
			jsonData.put(Constant.PARAM_PASSWORD, password);
			jsonData.put(Constant.PARAM_NICKNAME, nickname);
			if (mEmail != null) {
				jsonData.put(Constant.PARAM_NICKNAME, registerFirstViewData.get(Constant.REGISTER_DATA_NICKNAME));
			}
			if (mDrawableAvater != null) {
				jsonData.put(Constant.PARAM_AVATAR, photoName);
			}
			if (mAddress != null) {
				int locId = getLocationIdFromGLMServer();
				jsonData.put(Constant.PARAM_LOCATIONID, locId);
				jsonData.put(Constant.PARAM_LATITUDE, mAddress.getLatitude());
				jsonData.put(Constant.PARAM_LONGITUDE, mAddress.getLongitude());
			} else if (mGeoLocation != null) {
				jsonData.put(Constant.PARAM_LATITUDE, mGeoLocation[0]);
				jsonData.put(Constant.PARAM_LONGITUDE, mGeoLocation[1]);
			}
			Log.d("jsonData", jsonData.toString());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_REGISTER, jsonData);
		} catch (Exception e) {
			jsonResponse.setStatus(Status.ERR);
			e.printStackTrace();
		}
		if (jsonResponse.getStatus() == Status.ERR) {
			Toast.makeText(RegisterSecondViewActivity.this, getString(R.string.global_error_networkerr), Toast.LENGTH_LONG).show();
		} else {
			JSONObject data = jsonResponse.getData();
			
			try {
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					userid = data.getInt(Constant.RESP_USERID);
					UserInfoEntity userInfo = new UserInfoEntity();
					userInfo.setUserId(data.getInt(Constant.RESP_USERID));
					userInfo.setUserAccount(username);
					userInfo.setUserPassword(password);
					userInfo.setNickName(nickname);
					if (mDrawableAvater != null) {
						userInfo.setUserAvatar(mDrawableAvater);
					}
					if (mAddress != null) {
						userInfo.setLatitude(mAddress.getLatitude());
						userInfo.setLongitude(mAddress.getLongitude());
					} else if (mGeoLocation != null) {
						userInfo.setLatitude(mGeoLocation[0]);
						userInfo.setLongitude(mGeoLocation[1]);
					}
					UserInfoDAO.setUserInfo(getApplicationContext(), userInfo);
//					Intent intent = new Intent(getApplicationContext(), MainActivity.class);
//					this.startActivity(intent);
//					this.finish();
				} else {
					ViewsUtil.showErrorTip(RegisterSecondViewActivity.this, R.string.registertip_register_error);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		return status;
	}


	
	private int getLocationIdFromGLMServer() {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = new JSONResponse();
		int locId = -1;
		try {
			jsonData.put("name", MapMainActivity.getFormattedAddress(mAddress));
			jsonData.put("administrativeArea", mAddress.getAdminArea());
			jsonData.put("locality", mAddress.getLocality());
			jsonData.put("subLocality", mAddress.getSubLocality());
			jsonData.put("longitude", mAddress.getLongitude());
			jsonData.put("latitude", mAddress.getLatitude());

			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETLOCATIONID, jsonData);
		} catch (Exception e) {
			jsonResponse.setStatus(Status.ERR);
			e.printStackTrace();
		}
		if (jsonResponse.getStatus() != Status.ERR) {
			JSONObject data = jsonResponse.getData();
			int status = -1;
			try {
				status = data.getInt(Constant.RESP_STATUS);
				if (Constant.RESP_STATUS_SUCCESS == status) {
					locId = data.getInt(Constant.RESP_LOCID);
					Log.d(TAG, "loction id from glm ->" + locId);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return locId;
	}
}
